<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" v-show="showSearch" label-width="120px">
      <el-row :span="22">
        <el-col :span="4">
          <el-form-item :label="form.projectName" style="font-size:22px;font-weight:800" label-width="150px">
            <el-date-picker v-model="queryParams.dateMonth" type="month" placeholder="选择月" value-format="yyyy-MM-dd"
              format="yyyy 年 MM 月" @change="handleQuery">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="form.projectStatus == 2">
          <el-form-item label-width="10px">
            <el-button type="primary" size="small" @click="handleSwitch">{{ isCalendar ? '切换表格查看' : '切换日历查看'
            }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格查看 -->
    <div v-show="!isCalendar" @mousedown="startDrag" @mouseup="stopDrag" @mousemove="handleDrag" @mouseleave="stopDrag">
      <!-- height="1000" -->
      <el-table v-loading="loading" :data="form.staffList" ref="table" border  max-height="1000">
        <el-table-column label="员工姓名" align="center" prop="staffName" fixed="left"/>
        <el-table-column v-if="form.projectStatus == 2" label="员工职务" align="center" prop="projectDuitsName"
          fixed="left">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.cld_project_duits" :value="scope.row.projectDuitsName" />
          </template>
        </el-table-column>
        <el-table-column v-if="form.projectStatus == 2" label="岗位名称" align="center" prop="projectPostName" fixed="left">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.cld_project_post" :value="scope.row.projectPostName" />
          </template>
        </el-table-column>
        <el-table-column v-if="form.projectStatus == 2" label="项目小组" width="80px;" align="center" prop="groupName"
          fixed="left">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.cld_project_groups" :value="scope.row.groupName" />
          </template>
        </el-table-column>
        <el-table-column v-if="form.projectStatus == 2" label="员工状态" width="80px;" align="center" prop="staffStatus"
          fixed="left">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.staffStatus == 2" type="success">在岗</el-tag>
            <el-tag v-if="scope.row.staffStatus == 3" type="danger">离职</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="form.projectStatus == 2" label="基数/天" align="center" fixed="left">
          <template slot-scope="scope">
            {{ toMoney(scope.row.postWages / form.calendarList.length) }}
          </template>
        </el-table-column>
        <el-table-column label="合计" width="100px;" align="center" fixed="left">
          <template slot-scope="scope">
            {{ totalMoney(scope.row.dayData) }}
          </template>
        </el-table-column>
        <el-table-column align="center" :label="item.calendayDay + '日'" v-for="item in form.calendarList"
          :key="item.calendarId" width="120">
          <template slot-scope="{ row }">
            <div v-if="row.dayData[item.calendayDate]">
              <span v-if="row.dayData[item.calendayDate].detailsList">
                <el-button
                  :style="{ color: row.dayData[item.calendayDate].sumPay > 0 ? (row.dayData[item.calendayDate].isConfirm == 1 ? '#67c23a' : '#1890ff') : 'red' }"
                  size="mini" type="text" @click="handleViewPayDetails(row.dayData[item.calendayDate])">
                  {{ toMoney(row.dayData[item.calendayDate].sumPay) }}</el-button>
              </span>
              <span v-else> {{
                toMoney(row.dayData[item.calendayDate].sumPay) }}</span>
            </div>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <!-- 日历查看 -->
    <div v-show="isCalendar">
      <el-row :gutter="20">
        <!--小组岗位-->
        <el-col :span="3" :xs="24">
          <div class="head-container">
            <el-tree :data="groupJobOptions" :props="defaultProps" :expand-on-click-node="false" ref="tree"
              node-key="id" default-expand-all highlight-current @node-click="handleNodeClick">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}
                  <span v-if="data.staffId">- {{ data.postName }}</span>
                </span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <!--日历数据-->
        <el-col :span="21" :xs="24">
          <el-calendar :value="queryParams.dateMonth">
            <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
            <template slot="dateCell" slot-scope="{date, data}">
              {{ data.day.split('-').slice(1).join('-') }}
              <div v-if="staffForm[data.day]" class="slant-text-container">
                <div class="payTitle">实发薪酬</div>
                <div class="payValueClick" v-if="staffForm[data.day].detailsList"
                  @click="handleViewPayDetails(staffForm[data.day])">
                  {{ toMoney(staffForm[data.day].sumPay) }}
                </div>
                <div class="payValue" v-else>
                  {{ toMoney(staffForm[data.day].sumPay) }}
                </div>
                <div v-if="staffForm[data.day].isConfirm == 0" class="slant-text">
                  <el-tag type="danger">未确认</el-tag>
                </div>
              </div>
            </template>
          </el-calendar>
        </el-col>
      </el-row>
    </div>

    <el-dialog title="修改薪酬" :visible.sync="isViewPayOpen" width="40%" append-to-body :destroy-on-close="true">
      <el-table :data="payList" border>
        <el-table-column label="当前日期" align="center" width="150px;">
          <template slot-scope="scope">
            <span>{{ scope.row.year + '年' + scope.row.month + '月' + scope.row.day + '日' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="薪资类型" align="center" prop="payType" width="150px">
          <template slot-scope="scope">
            <dict-tag :options="payTypeOptions" :value="scope.row.payType" />
          </template>
        </el-table-column>
        <el-table-column label="涉及金额" align="center" prop="money" width="150px">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.money"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditPayDetails">保 存</el-button>
        <el-button @click="isViewPayOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTableCalendarList, batchEdit, getCalendarByStaffId } from "@/api/cld/CldPayDetails";
import { payTypeOptions } from '@/assets/staticDict'
import { selectGroupStaffByProjectId } from '@/api/cld/publicCommon'
export default {
  name: "CldPayDetails",
  dicts: ['cld_project_duits', 'cld_project_post', 'cld_project_groups'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 薪酬管理表格数据
      CldPayDetailsList: [],
      // 小组人员
      groupJobOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateMonth: new Date(),
        year: new Date().getFullYear(),
        month: (new Date().getMonth() + 1),
        projectId: this.$route.params.projectId
      },
      form: {},
      staffForm: {},
      payList: [],
      payTypeOptions: payTypeOptions,
      isViewPayOpen: false,
      isCalendar: false,
      // 当前选择人员
      staffId: null
    };
  },
  created() {
    this.getList();
    this.getGroupJobList();
  },
  methods: {
    /** 查询薪酬管理列表 */
    getList() {
      this.loading = true;
      getTableCalendarList(this.queryParams).then(response => {
        this.form = response.data;
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.table.bodyWrapper.scrollLeft = new Date().getDate() * 100 - 200;
          }, 1000)//必须是1000以上 才能生效
        });
        this.loading = false;
      });
    },
    // 查询小组人员
    getGroupJobList() {
      selectGroupStaffByProjectId(this.queryParams.projectId).then(res => {
        this.groupJobOptions = res.data;
      })
    },
    // 左侧人员选择
    handleNodeClick(e) {
      if (e.staffId) {
        this.staffId = e.staffId;
        this.handleSelectStaffPay()
      }
    },
    // 查询人员薪酬
    handleSelectStaffPay() {
      getCalendarByStaffId({
        ...this.queryParams,
        staffId: this.staffId
      }).then(res => {
        this.staffForm = res.data;
      })
    },
    // 切换显示形态
    handleSwitch() {
      this.isCalendar = !this.isCalendar;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.dateMonth) {
        this.queryParams.year = this.parseTime(this.queryParams.dateMonth, '{yyyy}');
        this.queryParams.month = this.parseTime(this.queryParams.dateMonth, '{mm}');
        console.log(this.queryParams.dateMonth)
      }
      this.queryParams.pageNum = 1;
      if (this.isCalendar) {
        this.handleSelectStaffPay()
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 薪酬明细查看
    handleViewPayDetails(e) {
      this.payList = e.detailsList;
      this.viewPayTitle = e.staffName + '-明细'
      this.isViewPayOpen = true;

    },
    // 修改薪酬明细
    submitEditPayDetails() {
      batchEdit(this.payList).then(res => {
        this.$modal.msgSuccess("修改成功");
        if (this.isCalendar) {
          this.handleSelectStaffPay()
        }
        this.isViewPayOpen = false;
        this.getList();
      })
    },
    // 薪资合计
    totalMoney(row) {
      // 初始化一个合计变量
      let totalSumPay = 0;
      // 遍历每个日期对象
      for (let date in row) {
        console.log(row[date])
        // 累加每个日期的 sumPay 值
        totalSumPay += row[date].sumPay;
      }
      return this.toMoney(totalSumPay);
    },
    //鼠标左右键控制横向滚动
    startDrag(event) {
      this.dragging = true;
      this.startX = event.clientX; // 记录鼠标按下的位置
      this.scrollLeft = this.$el.querySelector('.el-table__body-wrapper').scrollLeft; // 获取当前滚动位置
    },
    stopDrag() {
      this.dragging = false;
    },
    handleDrag(event) {
      if (this.dragging) {
        const dx = event.clientX - this.startX; // 计算鼠标移动的距离
        const newScrollLeft = this.scrollLeft - dx; // 计算新的滚动位置
        this.$el.querySelector('.el-table__body-wrapper').scrollLeft = newScrollLeft; // 设置新的滚动位置
      }
    }
  }
};
</script>
<style scoped>
.payTitle {
  text-align: center;
  font-size: 13px;
}

.payValueClick {
  text-align: center;
  font-size: 22px;
  cursor: pointer;
  color: #4d00ff;
}

.slant-text {
  position: absolute;
  right: 0;
  top: 0;

}

::v-deep .el-calendar__header {
  display: none;
}

::v-deep .el-calendar-table .el-calendar-day {
  position: relative;
}
</style>
